import 'package:duqing/components/article_card.dart';
import 'package:duqing/models/article_model.dart';
import 'package:duqing/services/article_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class ArticlePage extends StatefulWidget {
  const ArticlePage({Key key}) : super(key: key);

  @override
  _ArticlePageState createState() => _ArticlePageState();
}

class _ArticlePageState extends State<ArticlePage>
    with AutomaticKeepAliveClientMixin {
  List<ArticleItem> list = ArticleList([]).list;
  int page = 1;
  bool hasMore;
  int limit = 10;
  EasyRefreshController _controller;

  Future _onLoad() async {
    await _getArticleLists(push: true);
    _controller.finishLoad(noMore: !hasMore);
  }

  Future _onRefresh() async {
    page = 1;
   await _getArticleLists();
    _controller.resetLoadState();
  }

  Future _getArticleLists({bool push = false}) async {
    try {
      Map<String, dynamic> result =
          await ArticleService.getArticles(page: page);
      ArticleList listModel = ArticleList.fromJson(result['data']);
      print(listModel.list);
      setState(() {
        hasMore = page * limit > result['total'];
        page++;
        if (push) {
          list.addAll(listModel.list);
        } else {
          list = listModel.list;
        }
      });
    } catch (e, s) {
      print(s);
    }
  }

  @override
  void initState() {
    super.initState();
    _controller = EasyRefreshController();
  }

  @override
  void dispose() {
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return EasyRefresh(
      firstRefresh: true,
      controller: _controller,
      onRefresh: _onRefresh,
      onLoad: _onLoad,
      child: ListView.builder(
        itemCount: list.length,
        itemBuilder: (BuildContext context, int index) {
          return Column(
            children: [
              SizedBox(height: 8,),
              ArticleCard(articleItem:list[index])
            ],
          );
        },
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
